package com.flight.trans.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.flight.trans.global.Constant;
import com.flight.trans.global.ConstantInfo;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 消息服务
 */
public class RefreshService extends Service {

    private Intent mRefreshIntent;
    private int mCount;

    private long periodTime = 10 * 1000 ;

    private Timer mTimer = new Timer();
    private Task mTask = new Task() ;

    @Override
    public void onCreate() {
        super.onCreate();
        // 发送广播
        mRefreshIntent = new Intent(Constant.RefreshReceiver);
        // 定时发送任务
        mTimer.schedule(mTask , 0 , periodTime);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mCount = 0 ;
        senBroadcast();
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 执行定时任务
     */
    private class Task extends TimerTask {
        @Override
        public void run() {
            mCount++ ;
            senBroadcast();
        }
    }

    /**
     * 发送广播
     */
    private void senBroadcast(){
        try {
            if(mCount > ConstantInfo.RefreshTime)
                mCount = 0 ;

            mRefreshIntent.putExtra(Constant.INFO , mCount);
            sendBroadcast(mRefreshIntent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        if(mTimer != null){
            mTimer.cancel();
            mTimer = null;
        }

        if(mTask != null){
            mTask.cancel();
            mTask = null;
        }
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
